import Vue from 'vue'
import axios from 'axios';
import qs from 'qs';
import {config} from '../utils/config'
import store from '../store';

axios.defaults.withCredentials = true
axios.interceptors.request.use((config) => {
    let token = localStorage.getItem('access_token');
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config;
})
axios.interceptors.response.use((response) => {
    let token = response.headers.authorization;
    console.log(token);
    if (token) {
        // 如果 header 中存在 token，那么触发 refreshToken 方法，替换本地的 token
        store.commit('updateToken', token)
    }
    if (response.data) {
        return response.data
    } else {
        return response;
    }
}, (error) => {
    if (error.response) {
        console.log(error)
        if (error.response.status == 401) {
            store.commit('updateToken', {token:null})
        }
        let response = error.response
        let msg = response.data.msg
        return Promise.reject(msg);
    } else {
        return Promise.reject(error);
    }
})

export function post(url, data) {
    return axios.post(url, data);
}

export function get(url, params) {
    return axios.get(url, {params});
}